import {
  DashBoard
} from '../dashboard/DashBoard'
import {
  env
} from '../../.eslintrc';
import { ProgressBar } from '../component/progressBar';


export class Login {
  constructor() {
    // 初始化变量
    this.canvas = wx.createCanvas();
    this.context = this.canvas.getContext('2d');
    this.width = this.canvas.width;
    this.height = this.canvas.height;
    this.state = true;

    this.size_1 = this.width / 12;
    this.size_2 = this.width / 16;
    this.size_3 = this.height / 10;
    this.percentage = 10 / 12;

    this.button = [];

    this.isAnimating = true; // 用于控制动画的运行

    this.centerX = this.width / 2;
    this.centerY = this.height * this.percentage - this.size_3 * 1.5;

    this.centerSize = 30;
    this.outerSize = 30;
    this.outerCount = 18; // 外圈方块的数量
    this.outerRadius = this.size_3; // 外圈方块的半径

    this.centerAngle = 0; // 中心方块的旋转角度
    this.angle = 0;
    this.centerRotationSpeed = 0.03; // 中心方块旋转速度
    this.rotationSpeed = 0.02; // 旋转速度

    const systemInfo = wx.getSystemInfoSync();
    const wxVersion = systemInfo.version;
    const minVersin = '8.0.50';
    console.log('当前微信客户端版本：',wxVersion);
    if(this.compareVersion(wxVersion, minVersin) < 0) {
      //wx.updateWeChatApp();
    }

    this.onLoadImage(() => {
      this.init();
    });
  }

  onLoadImage(callback) {
    let loadedCount = 0;
    const totalImages = 6;
    this.background = wx.createImage();
    this.background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_2.png';
    this.background.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.pig_background = wx.createImage();
    this.pig_background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig1.png';
    this.pig_background.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.tree_background = wx.createImage();
    this.tree_background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/tree_icon_1.png';
    this.tree_background.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.animate_background = wx.createImage();
    this.animate_background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_3.png';
    this.animate_background.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.enterImage_1 = wx.createImage();
    this.enterImage_1.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig_icon_1.png';
    this.enterImage_1.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    this.enterImage_2 = wx.createImage();
    this.enterImage_2.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/comegame.png';
    this.enterImage_2.onload = () => {
      loadedCount++;
      checkIfAllLoaded();
    };

    const checkIfAllLoaded = () => {
      if (loadedCount === totalImages && callback) {
        callback();
      }
    };
  }

  init() {
    this.context.drawImage(this.background, 0, 0, this.width, this.height);
    this.draw();
  }

  draw() {
    this.login();
    this.drawCounsel();
    this.drawTitle();
    this.drawAnimate();
  }

  drawTitle() {
    let gradient = this.context.createLinearGradient(0, 0, this.width, 0);
    gradient.addColorStop(0, 'green');
    gradient.addColorStop(1, 'pink');

    this.context.shadowColor = 'rgba(0, 0, 0, 0.5)'; // 阴影颜色
    this.context.shadowOffsetX = 4; // 阴影水平偏移
    this.context.shadowOffsetY = 4; // 阴影垂直偏移
    this.context.shadowBlur = 5; // 阴影模糊半径

    this.context.fillStyle = gradient;

    this.context.font = `italic ${this.size_3}px Arial`;
    this.context.textAlign = 'center';
    this.context.fillText('救那只猪', this.width / 2, this.height * this.percentage - this.size_3 * 6);

    // this.context.strokeStyle = 'black';
    // this.context.lineWidth = 2;
    // this.context.strokeText('救那只猪', this.width / 2, this.height * this.percentage - this.size_3 * 6);
  }

  drawAnimate() {
    this.context.shadowColor = 'rgba(0, 0, 0, 0)'; // 阴影颜色
    this.context.shadowOffsetX = 0; // 阴影水平偏移
    this.context.shadowOffsetY = 0; // 阴影垂直偏移
    this.context.shadowBlur = 0; // 阴影模糊半径
    if (this.isAnimating) {
      this.context.clearRect(0, 0, this.width, this.height);

      this.context.drawImage(this.background, 0, 0, this.width, this.height);
      this.drawCounsel();
      this.drawTitle();

      this.drawCenterSquare();
      this.drawOuterTrees();

      this.centerAngle += this.centerRotationSpeed;
      this.angle += this.rotationSpeed;
    }

    requestAnimationFrame(() => this.drawAnimate());
  }

  drawCenterSquare() {
    this.context.save();
    this.context.translate(this.centerX, this.centerY);
    this.context.rotate(this.centerAngle);
    this.context.fillStyle = 'blue';
    this.context.drawImage(this.pig_background, -this.centerSize / 2, -this.centerSize / 2, this.centerSize, this.centerSize);
    this.context.restore();
  }

  drawOuterTrees() {
    for (let i = 0; i < this.outerCount; i++) {
      let angle = (i / this.outerCount) * 2 * Math.PI + this.angle;
      let x = this.centerX + this.outerRadius * Math.cos(angle);
      let y = this.centerY + this.outerRadius * Math.sin(angle);
      this.context.save();
      this.context.translate(x, y);
      this.context.drawImage(this.tree_background, -this.outerSize / 2, -this.outerSize / 2, this.outerSize, this.outerSize);
      this.context.restore();
    }
  }

  drawCounsel() {
    this.context.font = `${this.size_1}px Arial`;
    this.context.fillStyle = 'black';
    this.context.textAlign = 'center';
    this.context.fillText('《健康游戏忠告》', this.width / 2, this.height * this.percentage);

    this.context.font = `${this.size_2}px Arial`;
    this.context.fillText('抵制不良游戏，拒绝盗版游戏', this.width / 2, this.height * this.percentage + this.size_1);
    this.context.fillText('注意自我保护，谨防受骗上当', this.width / 2, this.height * this.percentage + this.size_1 + this.size_2);
    this.context.fillText('适度游戏益脑，沉迷游戏伤身', this.width / 2, this.height * this.percentage + this.size_1 + this.size_2 * 2);
    this.context.fillText('合理安排时间，享受健康生活', this.width / 2, this.height * this.percentage + this.size_1 + this.size_2 * 3);
  }

  login() {
    let _this = this;
    let _res = null;
    wx.offTouchStart();
    wx.login({
      success: (res) => {
        const code = res.code;
        wx.cloud.init({
          "env": 'prod-8gf88ck5bb3ddd38'
        })
        wx.cloud.callContainer({
          "config": {
            "env": "prod-8gf88ck5bb3ddd38"
          },
          "path": '/apis/token/getToken',
          "method": 'POST',
          "header": {
            "X-WX-SERVICE": env.service,
            "content-type": "application/json"
          },
          "data": {
            "code": code
          },
          timeout: 60000, //ms
          success: ({
            statusCode,
            header,
            data
          }) => {
            console.log(data)
            wx.setStorage({
              key: "AuthToken",
              data: data.AuthToken,
              success(res) {
                console.log(`Successfully set AuthToken: ${data.AuthToken}`);
              },
              fail(res) {
                console.log(`setStorage调用失败`);
              },
            });
            if(data.province !== '') {
            wx.setStorage({
              key: "province",
              data: data.province,
              success(res) {
                console.log(`Successfully set province: ${data.province}`);
              },
              fail(res) {
                console.log(`setStorage调用失败`);
              },
            });
          }
            if(data.city !== ''){
            wx.setStorage({
              key: "city",
              data: data.city,
              success(res) {
                console.log(`Successfully set city: ${data.city}`);
              },
              fail(res) {
                console.log(`setStorage调用失败`);
              },
            });
          }
            if(data.district !== ''){
            wx.setStorage({
              key: "district",
              data: data.district,
              success(res) {
                console.log(`Successfully set district: ${data.district}`);
              },
              fail(res) {
                console.log(`setStorage调用失败`);
              },
            });
          }
            const todaySkinId = data.todaySkinId;
            if(data.currentSkins !== ''){
            wx.setStorageSync('currentSkin', data.currentSkins);
            }
            if(data.userSkins !== undefined){
            wx.setStorageSync('userSkins', JSON.parse(data.userSkins));
            }
            if(todaySkinId !== ''){
            wx.setStorageSync('todaySkinId', todaySkinId);
            }
          },
          fail(err) {
            console.log(err)
          },
        });
        wx.getSetting({
          success(res) {
            if (res.authSetting['scope.userInfo']) {
              _this.onLoadOtherImage(()=>{
                _this.drawProgress(_this.canvas);
                setTimeout(() => {
                  _this.isAnimating = false; // 用于控制动画的运行
                  _this.onload(false);
                },3000)
              })
              // 用户已经授权，直接获取用户信息
              wx.cloud.callContainer({
                "config": {
                  "env": "prod-8gf88ck5bb3ddd38"
                },
                "path": `/apis/skin/selectUserSkins`,
                "header": {
                  'content-type': 'application/json',
                  'AuthToken': wx.getStorageSync("AuthToken"),
                  "X-WX-SERVICE": env.service
                },
                "method": "GET",
                success: (res) => {
                  wx.setStorage({
                    key: 'skinInfo',
                    data: res.data.skinInfo,
                    success: function (res) {
                      console.log(res);
                    },
                    fail: function (err) {
                      console.error('rankdata存储失败', err);
                    }
                  });
                  _this.records = wx.getStorageSync('skinInfo');
                  const skinId = wx.getStorageSync('currentSkin');
                  console.log(res.data.skinInfo);
                  res.data.skinInfo.forEach((skinInfo, index) => {
                    if (skinInfo.skinId == skinId) {
                      wx.setStorageSync('currentSkinImage', skinInfo.skinUrl);
                      const currentSkinImage = wx.getStorageSync('currentSkinImage');
                      console.log(currentSkinImage)
                    }
                    if(skinInfo.skinId == wx.getStorageSync('todaySkinId')) {
                      wx.setStorageSync('todaySkinImage', skinInfo.skinUrl);
                      const todaySkinImage = wx.getStorageSync('todaySkinImage');
                      console.log(todaySkinImage);
                    }
                  })
                },
                fail: console.warn,
              })
              wx.getUserInfo({
                success: (res) => {
                  console.log('success');
                },
                fail: (err) => {
                  console.error('failed', err);
                }
              });
            } else {
              _this.drawButton();
              // 设置授权按钮的点击事件
              _this.enter_1.onTap((res) => {
                if (res.errMsg === 'getUserInfo:ok') {
                  _res = res;
                  wx.getFuzzyLocation({
                    type: 'wgs84',
                    success(res) {
                      wx.cloud.callContainer({
                        "config": {
                          "env": "prod-8gf88ck5bb3ddd38"
                        },
                        "path": '/apis/users/createUserInfo',
                        "method": 'POST',
                        "header": {
                          'content-type': 'application/json',
                          'AuthToken': wx.getStorageSync("AuthToken"),
                          "X-WX-SERVICE": env.service
                        },
                        "data": {
                          'signature': _res.signature,
                          'encryptedData': _res.encryptedData,
                          'iv': _res.iv,
                          'rowData': _res.rowData,
                          'longitude': res.longitude,
                          'latitude': res.latitude
                        },
                        success: (res) => {
                          console.log(_res);

                          //JSON.parse(data);
                          console.log(res);
                          const data = res.data;
                          
                          wx.setStorage({
                            key: "province",
                            data: data.province,
                            success(res) {
                              console.log(`Successfully set province: ${data.province}`);
                            },
                            fail(res) {
                              console.log(`setStorage调用失败`);
                            },
                          });

                          wx.setStorage({
                            key: "city",
                            data: data.city,
                            success(res) {
                              console.log(`Successfully set city: ${data.city}`);
                            },
                            fail(res) {
                              console.log(`setStorage调用失败`);
                            },
                          });

                          wx.setStorage({
                            key: "district",
                            data: data.district,
                            success(res) {
                              console.log(`Successfully set district: ${data.district}`);
                            },
                            fail(res) {
                              console.log(`setStorage调用失败`);
                            },
                          });
                          const todaySkinId = data.todaySkinId;
                          wx.setStorageSync('currentSkin', data.currentSkins);
                          wx.setStorageSync('userSkins', JSON.parse(data.userSkins));
                          wx.setStorageSync('todaySkinId', todaySkinId);
                          wx.cloud.callContainer({
                            "config": {
                              "env": "prod-8gf88ck5bb3ddd38"
                            },
                            "path": `/apis/skin/selectUserSkins`,
                            "header": {
                              'content-type': 'application/json',
                              'AuthToken': wx.getStorageSync("AuthToken"),
                              "X-WX-SERVICE": env.service
                            },
                            "method": "GET",
                            success: (res) => {
                              wx.setStorage({
                                key: 'skinInfo',
                                data: res.data.skinInfo,
                                success: function (res) {
                                  console.log(res);
                                },
                                fail: function (err) {
                                  console.error('rankdata存储失败', err);
                                }
                              });
                              _this.records = wx.getStorageSync('skinInfo');
                              const skinId = wx.getStorageSync('currentSkin');
                              console.log(res.data.skinInfo);
                              res.data.skinInfo.forEach((skinInfo, index) => {
                                if (skinInfo.skinId == skinId) {
                                  wx.setStorageSync('currentSkinImage', skinInfo.skinUrl);
                                  const currentSkinImage = wx.getStorageSync('currentSkinImage');
                                }
                                if(skinInfo.skinId == wx.getStorageSync('todaySkinId')) {
                                  wx.setStorageSync('todaySkinImage', skinInfo.skinUrl);
                                  const todaySkinImage = wx.getStorageSync('todaySkinImage');
                                  console.log(todaySkinImage);
                                }
                              })
                            },
                            fail: console.warn,
                          })
                          // _this.drawProgress(_this.canvas);
                          _this.enter_1.destroy();
                          _this.enter_2.destroy();
                          _this.onLoadOtherImage(()=>{
                            _this.drawProgress(_this.canvas);
                            setTimeout(() => {
                              _this.isAnimating = false;
                              _this.onload(true);
                            },3000);
                          })
                        },
                        fail(err) {
                          console.error('用户信息创建失败', err);
                        }
                      })
                    },
                    fail(res) {
                      wx.showModal({
                        title: '获取位置信息失败',
                        content: '请打开定位服务，再尝试进入游戏',
                        complete: (res) => {
                          if (res.cancel) {
  
                          }
                          if (res.confirm) {
                           
                          }
                        }
                      })
                    }
                  })
                } else {
                  // 用户取消授权或授权失败
                  wx.showToast({
                    title: '授权失败，无法继续游戏',
                    icon: 'none',
                    duration: 2000
                  });
                }
              });
              _this.enter_2.onTap((res) => {
                if (res.errMsg === 'getUserInfo:ok') {
                  _res = res;
                  wx.getFuzzyLocation({
                    type: 'wgs84',
                    success(res) {
                      wx.cloud.callContainer({
                        "config": {
                          "env": "prod-8gf88ck5bb3ddd38"
                        },
                        "path": '/apis/users/createUserInfo',
                        "method": 'POST',
                        "header": {
                          'content-type': 'application/json',
                          'AuthToken': wx.getStorageSync("AuthToken"),
                          "X-WX-SERVICE": env.service
                        },
                        "data": {
                          'signature': _res.signature,
                          'encryptedData': _res.encryptedData,
                          'iv': _res.iv,
                          'rowData': _res.rowData,
                          'longitude': res.longitude,
                          'latitude': res.latitude
                        },
                        success: (res) => {
                          //JSON.parse(data);
                          console.log(res.data);
                          const data = res.data;
                          wx.setStorage({
                            key: "province",
                            data: data.province,
                            success(res) {
                              console.log(`Successfully set province: ${data.province}`);
                            },
                            fail(res) {
                              console.log(`setStorage调用失败`);
                            },
                          });

                          wx.setStorage({
                            key: "city",
                            data: data.city,
                            success(res) {
                              console.log(`Successfully set city: ${data.city}`);
                            },
                            fail(res) {
                              console.log(`setStorage调用失败`);
                            },
                          });

                          wx.setStorage({
                            key: "district",
                            data: data.district,
                            success(res) {
                              console.log(`Successfully set district: ${data.district}`);
                            },
                            fail(res) {
                              console.log(`setStorage调用失败`);
                            },
                          });
                          const todaySkinId = data.todaySkinId;
                          wx.setStorageSync('currentSkin', data.currentSkins);
                          wx.setStorageSync('userSkins', JSON.parse(data.userSkins));
                          wx.setStorageSync('todaySkinId', todaySkinId);
                          wx.cloud.callContainer({
                            "config": {
                              "env": "prod-8gf88ck5bb3ddd38"
                            },
                            "path": `/apis/skin/selectUserSkins`,
                            "header": {
                              'content-type': 'application/json',
                              'AuthToken': wx.getStorageSync("AuthToken"),
                              "X-WX-SERVICE": env.service
                            },
                            "method": "GET",
                            success: (res) => {
                              wx.setStorage({
                                key: 'skinInfo',
                                data: res.data.skinInfo,
                                success: function (res) {
                                  console.log(res);
                                },
                                fail: function (err) {
                                  console.error('rankdata存储失败', err);
                                }
                              });
                              _this.records = wx.getStorageSync('skinInfo');
                              const skinId = wx.getStorageSync('currentSkin');
                              console.log(res.data.skinInfo);
                              res.data.skinInfo.forEach((skinInfo, index) => {
                                if (skinInfo.skinId == skinId) {
                                  wx.setStorageSync('currentSkinImage', skinInfo.skinUrl);
                                  const currentSkinImage = wx.getStorageSync('currentSkinImage');
                                }
                                if(skinInfo.skinId == wx.getStorageSync('todaySkinId')) {
                                  wx.setStorageSync('todaySkinImage', skinInfo.skinUrl);
                                  const todaySkinImage = wx.getStorageSync('todaySkinImage');
                                  console.log(todaySkinImage);
                                }
                              })
                            },
                            fail: console.warn,
                          })
                          // _this.drawProgress(_this.canvas);
                          _this.enter_1.destroy();
                          _this.enter_2.destroy();
                          _this.onLoadOtherImage(()=>{
                            _this.drawProgress(_this.canvas);
                            setTimeout(()=>{
                              _this.isAnimating = false;
                              _this.onload(true);
                            },3000);
                          })
                        },
                        fail(res) {
                          wx.showModal({
                            title: '获取位置信息失败',
                            content: '请打开定位服务，再尝试进入游戏',
                            complete: (res) => {
                              if (res.cancel) {
      
                              }
                              if (res.confirm) {
                               
                              }
                            }
                          })
                        }
                      })
                    }
                  })
                } else {
                  // 用户取消授权或授权失败
                  wx.showToast({
                    title: '授权失败，无法继续游戏',
                    icon: 'none',
                    duration: 2000
                  });
                }
              });
            }
          },
          fail(err) {
            console.error('获取用户授权设置失败', err);
          }
        });
      },
      fail: (err) => {
        console.error('微信登录失败', err);
      }
    })
  }

  onLoadOtherImage(callback) {
    let loadedCount = 0;
    const totalImages = 8;

    //dashboard.js 7
    this.dashboardBackground = wx.createImage();
    this.dashboardBackground.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_2.png';
    this.dashboardBackground.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };
    this.dashboardEnterImage_1 = wx.createImage();
    this.dashboardEnterImage_1.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig_icon_1.png';
    this.dashboardEnterImage_1.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.dashboardEnterImage_2 = wx.createImage();
    this.dashboardEnterImage_2.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/comegame.png';
    this.dashboardEnterImage_2.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.settingImage = wx.createImage();
    this.settingImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/seting.png';
    this.settingImage.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.rankImage = wx.createImage();
    this.rankImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/chart.png';
    this.rankImage.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.bagImage = wx.createImage();
    this.bagImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/skinBag.png';
    this.bagImage.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.playerImage = wx.createImage();
    this.playerImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/playWay.png';
    this.playerImage.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    this.activityImage = wx.createImage();
    this.activityImage.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/activity.png';
    this.activityImage.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
    };

    const checkIfAllLoaded = () => {
      if (loadedCount === totalImages && callback) {
        callback();
      }
    };
  }

  onload(firstlogin) {
    wx.offTouchStart();
    this.canvas.width = this.canvas.width;
    const page = new DashBoard(this.canvas,firstlogin);
  }

  drawButton() {
    let _this = this;
    this.enter_1 = wx.createUserInfoButton({
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig_icon_1.png",
      style: {
        backgroundColor: 'transparent',
        left: _this.width / 2.4,
        top: _this.height * _this.percentage - _this.size_1 * 10,
        width: _this.width / 6,
        height: _this.size_1,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10
      },
    });
    this.enter_2 = wx.createUserInfoButton({
      type: "image",
      image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/comegame.png",
      style: {
        backgroundColor: '#CDAF95',
        left: _this.width / 3,
        top: _this.height * _this.percentage - _this.size_1 * 9,
        width: _this.width / 3,
        height: _this.size_1 * 2,
        textAlign: 'center',
        textColor: "black",
        borderRadius: 10
      }
    });
  }

  compareVersion(v1, v2) {
    const v1Parts = v1.split('.').map(Number);
    const v2Parts = v2.split('.').map(Number);
    
    for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
        const a = v1Parts[i] || 0;
        const b = v2Parts[i] || 0;
        if (a !== b) {
            return a - b;
        }
    }
    return 0;
  }

  drawProgress(canvas) {
    const progressBar = new ProgressBar(canvas);
    let currentProgress = 0;
    function updateProgress() {
      if (currentProgress <= 100) {
        progressBar.setProgress(currentProgress);
        currentProgress += 5; // 进度增加量
        requestAnimationFrame(updateProgress); // 请求下一个帧
      } 
    }
  
    updateProgress(); // 启动更新进度的循环
  }
}
